package com.accelstack.cmp.config;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.orm.jpa.support.OpenEntityManagerInViewFilter;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import java.util.Arrays;

/**
 * Web配置类
 */
@Configuration
public class WebConfig implements WebMvcConfigurer {
    
    @Value("${app.cors.allowed-origins:http://localhost:3000}")
    private String allowedOrigins;
    
    @Value("${app.cors.allowed-methods:GET,POST,PUT,DELETE,OPTIONS,PATCH}")
    private String allowedMethods;
    
    @Value("${app.cors.allowed-headers:*}")
    private String allowedHeaders;
    
    @Value("${app.cors.allow-credentials:true}")
    private boolean allowCredentials;
    
    @Value("${app.cors.max-age:3600}")
    private long maxAge;
    
    /**
     * 配置OpenEntityManagerInView过滤器
     * 确保在整个HTTP请求-响应周期内EntityManager保持打开状态
     * 这样可以在Controller和View层访问延迟加载的关联对象
     */
    @Bean
    public FilterRegistrationBean<OpenEntityManagerInViewFilter> openEntityManagerInViewFilter() {
        FilterRegistrationBean<OpenEntityManagerInViewFilter> filterBean = new FilterRegistrationBean<>();
        filterBean.setFilter(new OpenEntityManagerInViewFilter());
        filterBean.addUrlPatterns("/*");
        filterBean.setOrder(5);
        return filterBean;
    }
    
    /**
     * 配置CORS过滤器
     * 处理跨域请求
     */
    @Bean
    public FilterRegistrationBean<CorsFilter> corsFilterRegistration() {
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        CorsConfiguration config = new CorsConfiguration();
        
        // 允许的源
        String[] origins = allowedOrigins.split(",");
        config.setAllowedOrigins(Arrays.asList(origins));
        
        // 允许的HTTP方法
        String[] methods = allowedMethods.split(",");
        config.setAllowedMethods(Arrays.asList(methods));
        
        // 允许的请求头
        if ("*".equals(allowedHeaders)) {
            config.addAllowedHeader("*");
        } else {
            String[] headers = allowedHeaders.split(",");
            config.setAllowedHeaders(Arrays.asList(headers));
        }
        
        // 允许携带认证信息（Cookie、Authorization header等）
        config.setAllowCredentials(allowCredentials);
        
        // 暴露的响应头
        config.addExposedHeader("Authorization");
        config.addExposedHeader("X-Total-Count");
        config.addExposedHeader("X-Session-Id");
        
        // 预检请求缓存时间
        config.setMaxAge(maxAge);
        
        // 对所有路径应用CORS配置
        source.registerCorsConfiguration("/**", config);
        
        FilterRegistrationBean<CorsFilter> bean = new FilterRegistrationBean<>(new CorsFilter(source));
        bean.setOrder(0); // 设置为最高优先级
        
        return bean;
    }
    
    /**
     * 全局CORS配置（备用方案）
     * 与CorsFilter配合使用
     */
    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**")
            .allowedOriginPatterns(allowedOrigins.split(","))
            .allowedMethods(allowedMethods.split(","))
            .allowedHeaders(allowedHeaders.equals("*") ? new String[]{"*"} : allowedHeaders.split(","))
            .allowCredentials(allowCredentials)
            .maxAge(maxAge);
    }
}
